package oop.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oop.db.Database;

public class HistoryChoiceDAO {

	public static Map<Long, List<Long>> fetchChoices(long historyId)
			throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT ques_id, ans_id " +
					"FROM tblHistoryChoice " +
					"WHERE hist_id = ?";

			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, historyId);
			rs = stmt.executeQuery();

			Map<Long, List<Long>> choices = new HashMap<Long, List<Long>>();
			while (rs.next()) {
				long questionId = rs.getLong(1);
				long answerId = rs.getLong(2);

				if (!choices.containsKey(questionId)) {
					choices.put(questionId, new ArrayList<Long>());
				}
				choices.get(questionId).add(answerId);
			}

			return choices;
		} finally {
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static void addChoice(long historyId, long questionId, long answerId)
			throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "INSERT INTO tblHistoryChoice (hist_id, ques_id, ans_id) VALUES (?,?,?)";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, historyId);
			stmt.setLong(2, questionId);
			stmt.setLong(3, answerId);
			stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}
	
}
